﻿using Microsoft.Extensions.Configuration;
using System;
using Microsoft.Extensions.DependencyInjection;

namespace _066.配置系统
{
	public class Program
	{
		static void Main(string[] args)
		{
			// OldReadJson();

			NewReadJson();
		}
		
		/**
		 * DI 的方式读取
		 */
		private static void NewReadJson()
		{
			ServiceCollection services = new ServiceCollection();
			services.AddScoped<TestController>();

			ConfigurationBuilder configBuilder = new ConfigurationBuilder();
			configBuilder.AddJsonFile("config.json", optional: false, reloadOnChange: false);
			IConfigurationRoot configRoot = configBuilder.Build();

			// 绑定到根节点
			services.AddOptions().Configure<Config>(e => configRoot.Bind(e));

			using var sp = services.BuildServiceProvider();
			var c = sp.GetRequiredService<TestController>();
			c.Test();
		}

		/*
		 * 读取JSON
		 */
		private static void OldReadJson()
		{
			// JSON的读取
			ConfigurationBuilder configBuilder = new ConfigurationBuilder();
			// optional: true 表示 文件不存在就报错  false 就不报错
			// reloadOnChange 表示 配置文件如果修改就立即加载
			configBuilder.AddJsonFile("config.json", optional: false, reloadOnChange: false);
			IConfigurationRoot config = configBuilder.Build();
			string name = config["name"];
			string proxyAddress = config.GetSection("proxy:address").Value;
			// 得到对象
			Server server = config.GetSection("proxy").Get<Server>();
			Console.WriteLine($"name:{name}, address:{proxyAddress}");
			Console.WriteLine(server);
		}
	}

	public class Config
	{
		public string Name { get; set; }
		public string Age { get; set; }
		public Server Proxy { get; set; }

	}

	public class Server
	{
		public string Address { get; set; }
		public string Port { get; set; }

		public override string ToString()
		{
			return $"Address：{Address},Port:{Port}";
		}
	}
}
